import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Swiper, SwiperItem, Image, ScrollView, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { _apiGetBannerList, _apiGetRecommendChoice, _apiGetRecommendList } from '../../service/api'
import QQMapWX from '../../plugin/qqmap-wx-jssdk.min.js'
import Moment from '../../utils/moment'
import { QQMAPSDK_KEY } from '../../contans'
import { Tools } from '../../utils/tools'
import './index.styl'

const DEFAULT_POSITION_CITY_NAME: string = '北京'
const DEFAULT_POSITION__NAME_ADDRESS: string = '北京'
const DEFAULT_LATITYDE: number = 39.906930
const DEFAULT_LONGITUDE: number = 116.397570

interface PageState {
  bannerList: any[],
  positionCityName: string, // 当前位置的城市
  positionNameAddress: string, // 当前位置的详细描述
  latitude:  number, // 当前位置的 经度
  longitude: number, // 当前位置的 纬度
  isLoadData: false, // 页面数据加载进度
  isShowSettingPannel: false, // 显示手动打开设置
  hotelDate: {
    checkInDateFormat: string,
    checkInDateWeek: string,
    checkOutDateFormat: string,
    checkOutDateWeek: string
  },
  totalNights: number
}
type PageOwnProps = {
  hotel: {
    checkInDate: string,
    checkOutDate: string,
    city: string
  },
  common: {
    positionInfo: object
  }
}
interface PageDispatchProps {}
interface Hotel {
  props: PageState & PageDispatchProps & PageOwnProps
}
@connect(({ hotel }) => ({
  hotel: {
    checkInDate: hotel.checkInDate,
    checkOutDate: hotel.checkOutDate,
    city: hotel.city
  }
}))

class Hotel extends Component {
  constructor() {
    super(...arguments)
  }
  state: PageState = {
    bannerList: [],
    positionCityName: DEFAULT_POSITION_CITY_NAME, // 定位城市名
    positionNameAddress: DEFAULT_POSITION__NAME_ADDRESS, // 定位城市地址描述
    latitude: DEFAULT_LATITYDE, // 默认 天安门广场的经纬度
    longitude: DEFAULT_LONGITUDE, // 默认 天安门广场的经纬度
    hotelDate: {
      checkInDateFormat: '',
      checkInDateWeek: '',
      checkOutDateFormat: '',
      checkOutDateWeek: '',
    },
    totalNights: 1,
    isLoadData: false,
    isShowSettingPannel: false
  }
  config: Config = {
    backgroundColorBottom: '#F5F5F7'
  }
  async componentWillMount() {
    try {
      const catchedPositionInfo = Taro.getStorageSync('POSITION')

      if (catchedPositionInfo) {
        await Tools.setState.bind(this)({
          positionCityName: catchedPositionInfo.city,
          positionNameAddress: catchedPositionInfo.address_desc,
          latitude: catchedPositionInfo.latitude,
          longitude: catchedPositionInfo.longitude
        })
      }
      await await this._apiGetBannerList()
      setTimeout(_ => {
        this.setState({ isLoadData: true })
      }, 1000)
    } catch (err) {
      this.setState({ isLoadData: true })
    }
  }
  componentDidShow () {
    const { checkInDate, checkOutDate } = this.props.hotel
    const setHotelDate = {
      checkInDateFormat: Moment(new Date(checkInDate)).format('MM月DD日'),
      checkInDateWeek: Moment(new Date(checkInDate)).getWeek('day'),
      checkOutDateFormat: Moment(new Date(checkOutDate)).format('MM月DD日'),
      checkOutDateWeek: Moment(new Date(checkOutDate)).getWeek('day')
    }
    const setTotalNights = Moment().differDay(checkInDate, checkOutDate)

    this.setState({ hotelDate: setHotelDate, totalNights: setTotalNights })
  }

  async getLocation (event?) { // 我的位置
    event && event.stopPropagation()
    try {
      const { authSetting } = await Taro.getSetting()

      if (authSetting['scope.userLocation'] === false) return this.setState({ isShowSettingPannel: true })

      try {
        this.setState({ positionNameAddress: '努力定位中...' })
        const { latitude, longitude } = await Taro.getLocation({ altitude: true })
        const qqmapsdk = new QQMapWX({ key: QQMAPSDK_KEY })

        qqmapsdk.reverseGeocoder({
          location: {
            latitude,
            longitude
          },
          coord_type: 5,
          success: async res => {
            const addressRecommend = res.result.formatted_addresses.recommend
            const city = res.result.address_component.city
            const { lat, lng } = res.result.location
            const catchPositionObj = {
              city: city,
              address_desc: addressRecommend,
              latitude: lat,
              longitude: lng
            }
            Taro.setStorageSync('POSITION', catchPositionObj)
            await Tools.setState.bind(this)({ positionCityName: city, latitude: lat, longitude: lng })
            this.setState({ positionNameAddress: addressRecommend })
          },
          fail: ({ message }) => {
            Taro.hideLoading()
            Taro.showToast({ title: message || '接口错误', icon: 'none' })
          }
        })
      } catch (err) {
        this.setState({
          positionCityName: DEFAULT_POSITION_CITY_NAME,
          positionNameAddress: DEFAULT_POSITION__NAME_ADDRESS,
          latitude: DEFAULT_LATITYDE,
          longitude: DEFAULT_LONGITUDE
        })
        Taro.hideLoading()
      }
    } catch (err) {}
  }
  touchMoveBg(event) {
    return event.stopPropagation()
  }
  closePosition(event) {
    event.stopPropagation()
    this.setState({ isShowSettingPannel: false })
  }
  onResponseOpenSetting(e) {
    const openFlag = e.currentTarget.authSetting['scope.userLocation']
    if (openFlag) {
      this.setState({ isShowSettingPannel: false })
      this.getLocation()
    }
  }
  goToSelectCanleddar(event) {
    event.stopPropagation()
    Taro.navigateTo({ url: '/pages/hotel/calendar/index' })
  }
  goToSelectCityPage(event) {
    event.stopPropagation()
    Taro.navigateTo({ url: '/pages/hotel/select-city/index' })
  }

  async _apiGetBannerList() {
    const { data: resBanner } = await _apiGetBannerList({ navId: 8 })
    if (resBanner.flag === 0 && resBanner.data && resBanner.data.length) {
      this.setState({ bannerList: resBanner.data })
    }
  }

  render () {
    return (
      <View>
        {
          this.state.isLoadData &&
          <View className='header-wrapper'>
            <View className={`show-content ${this.state.isShowSettingPannel ? 'blur' : ''}`}>
              <Swiper className='swiper' autoplay interval={5000} duration={600} circular>
                {
                  this.state.bannerList.map((i, ind) => (
                    <SwiperItem key={ind}>
                      <Image className='img' mode='widthFix' src={i.img} />
                    </SwiperItem>
                  ))
                }
              </Swiper>
              <View className='search-box'>
                <View className='title'>
                  <Text>国内酒店</Text>
                  <Image mode='widthFix' src='https://image.yktour.com.cn/g1/M00/07/16/CgAMDFzs0RyAVHICAAAJrfu4e8E171.png' />
                </View>
                <View className='content-pannel'>
                  <View className='address-wrapper'>
                    <View className='address' onClick={this.goToSelectCityPage.bind(this)}>
                      <ScrollView className='txt' scrollX>{this.state.positionNameAddress}</ScrollView>
                      <Image mode='widthFix' src='http://m.yktour.com.cn/_nuxt/img/detail_right_button.6c87e3a.png' />
                    </View>
                    <View className='my-position' hover-class='my-position-hover' onClick={this.getLocation.bind(this)}>
                      <Image mode='widthFix' src='http://m.yktour.com.cn/_nuxt/img/%E5%AE%9A%E4%BD%8D@2x.fe64e49.png' />
                      <Text>我的位置</Text>
                    </View>
                  </View>
                  <View className='check-in-date-wrapper' onClick={this.goToSelectCanleddar.bind(this)}>
                    <View className='dates'>
                      <View className='date-box check-in'>
                        <Text>入住</Text>
                        <View>
                          <Text className='date'>{this.state.hotelDate.checkInDateFormat}</Text>
                          <Text>{this.state.hotelDate.checkInDateWeek}</Text>
                        </View>
                      </View>
                      <Text className='count'>共{this.state.totalNights}晚</Text>
                      <View className='date-box check-out'>
                        <Text>离店</Text>
                        <View>
                          <Text className='date'>{this.state.hotelDate.checkOutDateFormat}</Text>
                          <Text>{this.state.hotelDate.checkOutDateWeek}</Text>
                        </View>
                      </View>
                    </View>
                    <Image mode='widthFix' src='http://m.yktour.com.cn/_nuxt/img/detail_right_button.6c87e3a.png' />
                  </View>
                  <View className='trading-more'>
                    <ScrollView className='content no-data' scrollX>
                      {[1, 2, 3, 4].map((i, ind) => <Text key={ind}>热门商圈/行政区{i + 1}</Text>)}
                    </ScrollView>
                    <Image className='icon more del' mode='widthFix' src='' />
                  </View>
                  <View className='trading-more'>
                    <ScrollView className='content no-data' scrollX>
                      {[1, 2, 3, 4].map((i, ind) => <Text key={ind}>￥0-90{i + 1}</Text>)}
                    </ScrollView>
                    <Image className='icon more del' mode='widthFix' src='' />
                  </View>
                  <Button className='button-reset-css button-bg-gradient btn-search'>查询</Button>
                </View>
              </View>
          </View>
          </View>
        }
        {!this.state.isLoadData &&
          <View className='before-load-pannel'>
            <View className='banner'></View>
            {[1, 2, 3].map((_, ind) => <View key={ind} className='checked-pannel'></View>)}
            <View className='stars'>
              {[1, 2, 3, 4].map((_, ind) => <View key={ind}></View>)}
            </View>
            <View className='p-list'>
              {[1, 2, 3, 4, 5, 6, 7, 8].map((_, ind) => <View key={ind} className='item'></View>)}
            </View>
          </View>
        }
        {/* 位置 */}
        {this.state.isShowSettingPannel &&
          <View className='position-setting' onTouchMove={this.touchMoveBg.bind(this)}>
            <View className='pannel'>
              <View className='title'>提示</View>
              <View className='desc'>您取消了获取位置的权限，需要您重新打开</View>
              <Button className='button-reset-css button-bg-gradient btn' openType='openSetting' onOpenSetting={this.onResponseOpenSetting.bind(this)}>打开设置</Button>
              <Image className='icon-close' mode='widthFix' onClick={this.closePosition.bind(this)} src='http://newm.yktour.com.cn/_nuxt/img/search_clear.40f462e.png' />
            </View>
          </View>
        }
      </View>
    )
  }
}

export default Hotel